package com.antd.common.core.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.antd.admin.api.entity.SysDict;
import com.antd.admin.api.entity.SysDictItem;
import com.antd.common.core.constant.Constant;
import lombok.experimental.UtilityClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author 子丶沫
 * @since 2020-12-22 17:23
 */
@UtilityClass
public class DictUtil {

    /**
     * 设置字典
     *
     * @param key 参数key
     * @param dictList 数据集合
     */
    public void setDictCache(String key, List<SysDictItem> dictList){
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key),dictList);
    }

    /**
     * 获取缓存集合
     * @param key key
     * @return list
     */
    @SuppressWarnings("unchecked")
    public List<SysDictItem> getDictCache(String key){
        Object object = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if(ObjectUtil.isNotNull(object)){
            return (List<SysDictItem>) object;
        }
        return null;
    }

    /**
     * 获取字典label
     * @param dictType 字典类型
     * @param value 数据值
     * @return str
     */
    public String getDictLabel(String dictType,String value){
        List<SysDictItem> dictCache = getDictCache(dictType);
        if(CollectionUtil.isNotEmpty(dictCache)){
            final Optional<SysDictItem> any = dictCache.stream().filter(dict -> dict.getItemValue().equals(value)).findAny();
            if(any.isPresent()){
                return any.get().getItemText();
            }
        }
        return "";
    }
    /**
     * 清空字典缓存
     */
    public static void clearDictCache()
    {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(Constant.SYS_DICT_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }
    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey)
    {
        return Constant.SYS_DICT_KEY + configKey;
    }
}
